package cn.taobaoke.restful.interceptor;

import cn.taobaoke.restful.exception.TBKException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;

/**
 * StarExceptionHandler.
 * +-----------------------------------------------------------------------------------------------+
 * |类名称: StarExceptionHandler                                                                  |
 * |创建时间: 2016-08-06T17:33:00                                                                   |
 * |功能简介:                                                                                       |
 * |参考链接:                                                                                       |
 * +-----------------------------------------------------------------------------------------------+
 *
 * @author chuan.lu
 */
public class TbkExceptionHandler implements HandlerExceptionResolver {

    private static Logger logger = LogManager.getLogger(TbkExceptionHandler.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest,
                                         HttpServletResponse response, Object o,
                                         Exception e) {
        logger.info("request => {}", httpServletRequest.getRequestURI());
        logger.error("star error => " + e.getMessage(), e);

        ModelAndView modelAndView = new ModelAndView();

        TBKException tbkException;
        if (!(e instanceof TBKException)) {
            tbkException = new TBKException(e.getMessage());
            logger.info("[error]" + e.getMessage());
        } else {
            tbkException = (TBKException) e;
        }

        logger.info("error => " + e.getMessage());

        modelAndView.addObject("error", tbkException);
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=UTF-8");
            Writer writer = response.getWriter();
            writer.write(tbkException.toJson());
            writer.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        return null;
    }
}
